package com.bodu.global.config.handler;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.signers.JWTSignerUtil;
import com.bodu.core.cache.CacheService;
import com.bodu.core.entity.CommonEntity;
import com.bodu.core.entity.result.RStateEnum;
import com.bodu.core.entity.result.Result;
import com.bodu.global.security.LoginUser;
import com.bodu.system.entity.po.PermitPo;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author gaoya
 * @Description 登录成功
 * @date 2022 - 10 - 13 00:14:53
 */
@Component
public class SuccessHandler implements AuthenticationSuccessHandler {

    private final CacheService cacheService;

    public SuccessHandler(CacheService cacheService) {
        this.cacheService = cacheService;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException {
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        String token =  JWT.create()
                .setPayload("sub", loginUser.getId())
                .setPayload("name", loginUser.getUsername())
                .setPayload("admin", true)
                .setSigner(JWTSignerUtil.none())
                .sign();
        cacheService.add(token, loginUser);

        Map<String, Object> data = MapUtil.newHashMap();
        data.put("token", token);
        data.put("user", userInfo(loginUser));

        httpServletResponse.setStatus(RStateEnum.SUCCESS.getCode());

        httpServletResponse.setContentType("application/json;charset=UTF-8");
        httpServletResponse.getWriter().print(JSONUtil.parse(Result.success("登录成功！",data)));
    }

    private Map<String ,Object> userInfo(LoginUser loginUser) {
        Map<String, Object> userInfo = MapUtil.newHashMap();
        userInfo.put("id", loginUser.getId());
        userInfo.put("name", loginUser.getUsername());
        userInfo.put("roles", loginUser.getRolePos().stream().filter(role -> ObjectUtil.isNotEmpty(role)).map(CommonEntity::getId).collect(Collectors.toSet()));
        userInfo.put("permits", loginUser.getPermitPos().stream().filter(permit -> ObjectUtil.isNotEmpty(permit)).map(PermitPo::getAuthority).collect(Collectors.toSet()));
        return userInfo;
    }
}
